package com.soap.service.impl;

import com.soap.commons.ESSourceCommons;
import com.soap.commons.ReturnCommons;
import com.soap.service.UserSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author ZhangPY
 * @Date 2020/7/2
 */
@Service
public class UserSearchServiceImpl implements UserSearchService {

    @Autowired
    RestHighLevelClient client;

//    @Value("${overun.elasticsearch.personIndices}")
    private String personIndices;

//    @Value("${overun.elasticsearch.types}")
    private String type;

    @Override
    public String batchInsertUser(List<Map<String, Object>> mapList) {
        BulkRequest request = new BulkRequest();

        for (Map<String,Object> map : mapList) {
            IndexRequest indexRequest= new IndexRequest(personIndices, type, map.get("id").toString()).source(map);
            request.add(indexRequest);
        }


        try {
            BulkResponse bulkItemResponses = client.bulk(request, RequestOptions.DEFAULT);

            for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
                if (bulkItemResponse.isFailed()) {
                    BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                    System.out.println("批量插入失败"+failure.getStatus());
                }
            }

            ReturnCommons.getSuccess();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ReturnCommons.getFail();
    }

    @Override
    public String createUserIndex(String source) {
        if (StringUtils.isBlank(source)) {
            source = ESSourceCommons.userSource;
        }
        /** 创建索引对象 */
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(personIndices);
        /** 设置参数 number_of_replicas 是数据备份数，如果只有一台机器，设置为0 、number_of_shards  是数据分片数，默认为5，有时候设置为3 */
        createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
        /** 指定映射 */
        createIndexRequest.mapping(type, source, XContentType.JSON);
        /** 操作索引的客户端 */
        IndicesClient indices = client.indices();
        boolean acknowledged = false;

        try {
            /** 执行创建索引库 */
            CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
            /** 得到响应 */
            acknowledged = createIndexResponse.isAcknowledged();

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (acknowledged) {
            return ReturnCommons.getSuccess();
        } else {
            return ReturnCommons.getFail();
        }
    }


    @Override
    public String insertUser(Map<String, Object> jsonMap) {

        /** 创建索引创建对象 可设置es主键 _id */
        IndexRequest indexRequest = new IndexRequest(personIndices,type, jsonMap.get("id").toString());
        /** 文档内容 */
        indexRequest.source(jsonMap);

        try {
            /** 通过client进行http的请求 */
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            DocWriteResponse.Result result = indexResponse.getResult();
            return ReturnCommons.getSuccess(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ReturnCommons.getFail();
    }
}
